import { _decorator, Component, Layers, Node, random, resources, Sprite, SpriteFrame, UI, UITransform } from 'cc'
import { TileManager } from './TileManager'
import { CreateUINode, randomByRange } from '../../Utils'
import DataManager from '../../Runtime/DataManager'
import ResourceManager from '../../Runtime/ResourceManager'

const { ccclass, property } = _decorator
@ccclass('TileMapManager')
export class TileMapManager extends Component {

 async init(){
  const { mapInfo } = DataManager.Instance
  const spriteFrames = await ResourceManager.Instance.loadDir('texture/tile/tile')
  for(let i =0;i < mapInfo.length;i++){
    const column =mapInfo[i]
    for(let j=0;j<column.length;j++){
      const item = column[j]
      if(item.src ===null || item.type ===null){
        continue
      }

      let number = item.src
      if((number === 1|| number === 5 || number === 9 )&& i %2 === 0 && j %2 === 0){
        number +=randomByRange(0,4)
      }
      const imgSrc =`tile (${number})`
      const node = CreateUINode()
      const spriteFrame = spriteFrames.find(v=>v.name ===imgSrc) || spriteFrames[0]

      //调用TileManager脚本
      const tileManager = node.addComponent(TileManager)
      tileManager.init(spriteFrame,i,j)

      node.setParent(this.node)
    }
  }
 }

}

